package top.hunfan.kindle.jikeshijian.video;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import top.hunfan.kindle.utils.IOUtils;

public class CrawlVideo {

    public static final Logger log = LoggerFactory.getLogger(CrawlVideo.class);

    private static final ExecutorService crawlerService = Executors.newFixedThreadPool(5);

    private static RestTemplate restTemplate = new RestTemplate();

    public static HttpHeaders getHeaders(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        headers.add("Referer", "https://time.geekbang.org/column/article/0?cid=81");
        //自行替换为已订阅账号的cookie
        headers.add("Cookie", "XXXXX");
        headers.add("Accept", "application/json, text/plain, */*");
        return headers;
    }

    public static void main(String[] args) throws IOException {
        HttpHeaders headers = getHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("cid", "156");
        body.put("size", 200);
        body.put("prev", 0);
        body.put("order", "earliest");
        body.put("sample", false);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(body), headers);
        JSONObject object = restTemplate.postForObject("https://time.geekbang.org/serv/v1/column/articles", requestEntity, JSONObject.class);
        JSONArray arr = object.getJSONObject("data").getJSONArray("list");
        List<Video> ids = new LinkedList<>();
        for(int i=0;i < arr.size();i++){
            ids.add(new Video(arr.getJSONObject(i).getString("article_title")
                    .replaceAll(" ", "")
                    .replaceAll("\\|", "-"),
                    arr.getJSONObject(i).getString("video_media")));
        }
        List<CompletableFuture<Boolean>> tasks = ids.stream()
                .map(id -> CompletableFuture.supplyAsync(() -> getChapterInfo(id), crawlerService))
                .collect(Collectors.toList());
        List<Boolean> result = tasks.stream().map(CompletableFuture::join)
                .collect(Collectors.toList());
        System.out.println("all finish,size:" + result.size());
    }

    public static void exec(String media, String title, String savePath) {
        String cmdStr = String.format("bin\\ffmpeg.exe  -i %s -vcodec copy -acodec copy -absf aac_adtstoasc %s",
                media, savePath + title + ".mp4");
        InputStream is = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        String textLine = "";

        try {
            Process process = Runtime.getRuntime().exec(cmdStr);
            is = process.getErrorStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            while((textLine = br.readLine()) != null) {
                log.debug(textLine);
            }

            log.debug("exec finish!");
        } catch (IOException var12) {
            log.error("exec error!", var12);
        } finally {
            IOUtils.close(br);
            IOUtils.close(isr);
            IOUtils.close(is);
        }

    }

    public static Boolean getChapterInfo(Video video){
        JSONObject object = JSON.parseObject(video.getVideoMedia());
        System.out.println(object.getJSONObject("hd").getString("url"));
        exec(object.getJSONObject("hd").getString("url"), video.getTitle(), "D:\\tmp7\\玩转Spring全家桶\\");
        return true;
    }

}

